﻿using System;
using System.Text;
using System.Threading;
using SimplePipeHelper.Client;

namespace NetFrameworkClient
{
    class PipeClientHelper
    {
        private SimplePipeClient _pipeClient;

        public void StartTest(string pipeName)
        {
            //pipeName = pipeName.Replace("\\\\.\\pipe\\", "");
            _pipeClient = new SimplePipeClient {PipeName = pipeName};
            _pipeClient.PipeClientConnect += OnPipeClientConnect;
            _pipeClient.PipeClientClosed += OnPipeClientClosed;
            _pipeClient.PipeServerClosed += OnPipeServerClosed;
            _pipeClient.DataReceived += OnDataReceived;

            System.Console.WriteLine($"Connect pipe server: {pipeName}...");
            _pipeClient.Connect();
        }

        public void StopTest()
        {
            (_pipeClient as IDisposable)?.Dispose();
            _pipeClient = null;
        }

        private void OnPipeClientConnect(SimplePipeClient pipeClient, bool result)
        {
            System.Console.WriteLine($"OnPipeClientConnect: {pipeClient.PipeName}, {result}");

            if (result)
            {
                Thread.Sleep(10);

                var message = "pipe client send message to pipe server.";
                var bytes = Encoding.UTF8.GetBytes(message);
                _pipeClient?.SendMessage(bytes);
                Thread.Sleep(1);
                _pipeClient?.SendMessage(bytes);
                Thread.Sleep(1);
                _pipeClient?.SendMessage(bytes);
            }
            else
            {
                System.Console.WriteLine($"LastErrorMessage: {_pipeClient.LastErrorMessage}");
            }
        }

        private void OnPipeClientClosed(SimplePipeClient pipeClient)
        {
            System.Console.WriteLine($"OnPipeClientClosed {pipeClient.PipeName}");
        }

        private void OnPipeServerClosed(SimplePipeClient pipeClient)
        {
            System.Console.WriteLine($"OnPipeServerClosed {pipeClient.PipeName}");
            StopTest();
        }

        private void OnDataReceived(SimplePipeClient pipeClient, byte[] buffer)
        {
            System.Console.WriteLine($"OnDataReceived {pipeClient.PipeName}");

            var message = Encoding.UTF8.GetString(buffer);
            System.Console.WriteLine($"Message: {message}");
        }
    }
}
